<?php

namespace app\admin\controller;

use app\common\Helper;

use app\admin\model\Advertise as AdvertiseMdl;
use app\admin\model\Advertiselocal;
use app\admin\model\Advertiselocalconnect;

use think\Db;
use think\Exception;
use think\Request;

class Advertise extends Base
{

    public function getlist(){
        $params = $this->request->param();
        $where = [
            'status' => ['neq', 3],
            'payStatus' => 1
        ];
        if(isset($params['advertiseTitle']) && $params['advertiseTitle']){
            $where['advertiseTitle'] = ['like', "%{$params['advertiseTitle']}%"];
        }

        $model = model('Advertise');
        $list = $model->where($where)->order('createTime DESC')->paginate(10);
        $total = $model->where($where)->count();

        return $this->fetch('',[
            'datas' => $list,
            'total' => $total,
            'formget' => $_GET
        ]);
    }

    /**
     * 上架/下架
     */
    public function handle(){
        $param = $this->request->param();
        $model = model('Advertise');

        $id = $param['id'];
        if($param['type'] == 1){
            // 上架
            // 判断广告位是否已删除
            $advertiselocalId = Advertiselocalconnect::where('advertiseId', $id)->value('advertiseLocalId');
            if($advertiselocalId){
                $advertiselocal = Advertiselocal::where('id', $advertiselocalId)->find();
                if($advertiselocal['status'] == 2){
                    return show(config('status.error_code'), '该广告的广告位已被删除，无法上架', '该广告的广告位已被删除，无法上架');
                }
            }

            $data['status'] = 1;
            $result = $model->allowField(true)->save($data, ['id' => $id]);
        }else{
            // 下架
            $data['status'] = 2;
            $result = $model->allowField(true)->save($data, ['id' => $id]);
        }

        if($result !== false){
            return show(config('status.success_code'), '操作成功', '操作成功');
        }else{
            return show(config('status.error_code'), '操作失败', $model->getError());
        }
    }

    /**
     * 删除
     */
    public function del(Request $request){
        $model = model($this->model);
        if($request->isPost()){
            $param = $request->param();
            $id = $request->param('id');
            if(isset($_POST['ids'])){
                // 删除多条
                $ids = $param['ids'];
                $result = $model->whereIn('id', $ids)->update(['status' => 3]);
            }else if($id){
                // 删除一条
                $result = $model->where('id', $id)->update(['status' => 3]);
            }

            if($result === false){
                return show(config('status.error_code'),'删除失败','删除失败');
            }else{
                return show(config('status.success_code'),'删除成功','删除成功');
            }
        }
    }

}